from django_ipgeobase.models import IPGeoBase
from annoying.functions import get_object_or_None

from core.models import City


def register(credential, ip):
    user = credential.register()
    ipgeobases = IPGeoBase.objects.by_ip(ip)
    if ipgeobases.exists():
        ipgeobase = ipgeobases[0]
        city = get_object_or_None(City, name=ipgeobase.city)
        if city is not None:
            user.cities.add(city.id)
            user.save()
    return user
